package be.dch.srtm2osm;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import uk.me.parabola.splitter.Area;
import crosby.binary.file.BlockInputStream;

public class Srtm2OsmLauncher {

    private final Srtm2OsmConfig config;

    public Srtm2OsmLauncher(final Srtm2OsmConfig config) {
	if (!config.validate()) {
	    throw new IllegalArgumentException("Invalid Configuration.");
	}
	this.config = config;
    }

    public void process(final String inputFilename) throws IOException {

	if (inputFilename.endsWith(".pbf")) {
	    // Is it a binary file?
	    final Area area = this.calculateArea(inputFilename);
	    if (area == null) {
		// TODO throw own exception
		throw new IllegalArgumentException("Wrong pbf-file.");
	    }

	    final Srtm2Osm srtm2Osm = new Srtm2Osm(area, this.config.getOutputFile());
	    srtm2Osm.run();

	} else {
	    throw new IllegalArgumentException("Only pbf-files are supported. ");
	}

    }

    private Area calculateArea(final String filename) {
	try {
	    final File file = new File(filename);
	    final BinaryMapParserArea binaryMapParser = new BinaryMapParserArea();
	    final BlockInputStream blockinput = (new BlockInputStream(new FileInputStream(file), binaryMapParser));
	    try {
		blockinput.process();
	    } catch (final RuntimeException e) {
		//
	    } finally {
		blockinput.close();
	    }
	    return binaryMapParser.getArea();
	} catch (final IOException e) {
	    // TODO
	    e.printStackTrace();
	}
	return null;
    }

}
